package com.zkw.nio;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;

/**
 * Created by Administrator on 2016/4/30 0030.
 * 客户端-selector
 */
public class SelectorSocketChannelDemo {
    public static void startClient(){
        try {
            SocketChannel socketChannel = SocketChannel.open();
            socketChannel.connect(new InetSocketAddress(8999));
            //主要设置成非阻塞
            socketChannel.configureBlocking(false);
            Selector selector = Selector.open();
            socketChannel.register(selector, SelectionKey.OP_READ);
            ByteBuffer byteBuffer = ByteBuffer.wrap("hello 我是客户端".getBytes("UTF-8"));
            socketChannel.write(byteBuffer);
            byteBuffer.clear();
            new ClientThread(selector).start();



        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        startClient();
    }
}
